package com.puzzlebazar.client.util;

import java.util.Date;

import com.google.gwt.i18n.client.DateTimeFormat;

public class DateUtil {

	static private DateTimeFormat stdFormat  = null;
	static private DateTimeFormat fullFormat = null; 

	static private DateTimeFormat getStdFormat() {
		if( stdFormat == null )
			stdFormat = DateTimeFormat.getFormat("M/d/y");
		return stdFormat;
	}
	
	static private DateTimeFormat getFullFormat() {
		if( fullFormat == null )
			fullFormat = DateTimeFormat.getFormat("M/d/y  h:mm a");
		return fullFormat;
	}
	
	/**
	 * Creates a string representing a nicely formatted absolute date.
	 * 
	 * @param date The date to convert
	 * @param currentTime The current time, in millisecond (use System.currentTimeMillis() )
	 * @return A formatted string
	 */
	public static String absoluteDate(Date date) {
		if( date == null )
			return "Unknown date";
		return DateUtil.getFullFormat().format(date);		
	}

	/**
	 * Creates a string representing a nicely formatted relative date. The string
	 * will look like :
	 * -  "seconds ago"
	 * -  "1, 2, 3, ..., 59 minutes ago"
	 * -  "1, 2, 3, ..., 23 hours ago"
	 * -  "1, 2, 3, ..., 9 days ago"
	 * -  "on xx/xx/xx"
	 * 
	 * Time is rounded ==> 1.1 rounded to 1     1.6 rounded to 2
	 * 
	 * @param date The date to convert
	 * @param currTime The current time, in millisecond (use System.currentTimeMillis() )
	 * @return A formatted string
	 */
	public static String relativeDate(Date date, long currTime) {
		
		if( date == null )
			return "on an unspecified date";
	
		long diff = currTime - date.getTime();
		
		// If it's in the past
		if( diff >= 0 ) {
	
			// Convert to minutes
			diff = (diff + 30000) / 60000;
	
			if( diff == 0 ) return "seconds ago";
			if( diff == 1 ) return "1 minute ago";
			if( diff < 60 ) return diff + " minutes ago";
	
			// Convert to hours
			diff = (diff + 30) / 60;
			if( diff == 1 ) return "1 hour ago";
			if( diff < 24 ) return diff + " hours ago";
	
			// Convert to days
			diff = (diff + 12) / 24;
			if( diff == 1 ) return " yesterday";		
			if( diff < 10 ) return diff + " days ago";		
		}		
		
		return "on " + DateUtil.getStdFormat().format(date);		
	}
	
	/**
	 * Compare two dates (possibly null).
	 * A null date is considered to be 00/00/0000
	 * 
	 * @param a The first date to compare
	 * @param b The second date to compare
	 * @return A negative value if data a comes before date b. 
	 *         A positive value if date a comes after date b. 
	 *         0 if the dates are equal.
	 */
	public static int compareDate( Date a, Date b ) {
		if( a == null ) {
			if( b == null ) 
				return 0;
			return -1;
		}
		if( b == null )
			return 1;
		
		return a.compareTo( b );
		
	}

}
